<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>购物车</h2>
      <span class="badge">共 {{ cartNum }} 件商品</span>
    </div>

    <div class="cart-body">
      <div class="cart-control">
        <label class="select-all">
          <input 
            type="checkbox" 
            :checked="isAllSelected" 
            @change="toggleAllSelection"
          >
          <span class="checkmark"></span>
          <span>全选</span>
        </label>
      </div>

      <div class="items-container">
        <div 
          v-for="(item, index) in product" 
          :key="item.productId + '-' + index" 
          class="cart-item"
        >
          <label class="item-select">
            <input 
              type="checkbox" 
              v-model="item.selected"
              @change="updateSelection"
            >
            <span class="checkmark"></span>
          </label>

          <div class="item-image">
            <img :src="item.productMainImg" :alt="item.productName">
          </div>

          <div class="item-details">
            <h3 class="item-name">{{ item.productName }}</h3>
            <p class="item-desc">{{ item.productBrand }} {{ item.productColor }} {{ item.productSize }}</p>
            <div class="item-tags">
              <span class="tag">{{ item.productType }}</span>
            </div>
          </div>

          <div class="item-pricing">
            <div class="price-row">
              <span class="current-price">¥{{ (item.productPrice).toFixed(2) }}</span>
              <span class="original-price" v-if="item.productPrice < item.productPrice * 1.2">
                ¥{{ (item.productPrice * 1.2).toFixed(2) }}
              </span>
            </div>
            <div class="quantity-control">
              <button 
                class="qty-btn"
                @click="adjustQuantity(item.productId, -1)"
                :disabled="carts[index].productNum <= 1"
              >-</button>
              <span class="quantity">{{ carts[index].productNum }}</span>
              <button class="qty-btn" @click="adjustQuantity(item.productId, 1)">+</button>
            </div>
          </div>

          <button class="remove-btn" @click="removeItem(item.productId)">×</button>
        </div>

        <div v-if="product.length === 0" class="empty-cart">
          <p>购物车空空如也</p>
          <button class="browse-btn">去逛逛</button>
        </div>
      </div>

      <div class="coupon-selector" v-if="selectedCount > 0">
        <button 
          class="coupon-trigger"
          @click="showCouponModal = true"
        >
          <span v-if="!selectedCoupon">使用优惠券</span>
          <span v-else class="selected-coupon">
            已选优惠券: 减¥{{ (selectedCoupon.mycouponPrice).toFixed(2) }}
            <span class="remove-coupon" @click.stop="removeCoupon">×</span>
          </span>
        </button>
      </div>
    </div>

    <div class="checkout-bar" :class="{ active: selectedCount > 0 }">
      <div class="price-summary">
        <div class="summary-row">
          <span>商品总价</span>
          <span>¥{{ (totalPrice).toFixed(2) }}</span>
        </div>
        <div class="summary-row" v-if="selectedCoupon">
          <span>优惠券</span>
          <span class="discount">-¥{{ (selectedCoupon.mycouponPrice).toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>应付总额</span>
          <span class="final-price">¥{{ (finalPrice).toFixed(2) }}</span>
        </div>
      </div>
      <button 
        class="checkout-btn"
        :disabled="selectedCount === 0"
        @click="handleCheckout"
      >
        结算({{ selectedCount }})
      </button>
    </div>

    <div class="coupon-modal" v-if="showCouponModal" @click.self="showCouponModal = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择优惠券</h3>
          <button class="close-btn" @click="showCouponModal = false">×</button>
        </div>
        <div class="modal-body">
          <div 
            v-for="coupon in availableCoupons" 
            :key="coupon.mycouponId"
            class="coupon-card"
            :class="{ 'selected': selectedCoupon?.mycouponId === coupon.mycouponId }"
            @click="selectCoupon(coupon)"
          >
            <div class="coupon-value">
              <span>¥</span>
              <span class="amount">{{ (coupon.mycouponPrice).toFixed(2) }}</span>
            </div>
            <div class="coupon-details">
              <div class="coupon-name">{{ coupon.mycouponName || parseCouponName(coupon) }}</div>
              <div class="coupon-condition">满{{ parseMinCondition(coupon.yy) }}元可用</div>
              <div class="coupon-expiry">有效期至{{ formatDate(coupon.xx) }}</div>
            </div>
            <div class="coupon-selector">
              <input 
                type="radio" 
                name="coupon" 
                :checked="selectedCoupon?.mycouponId === coupon.mycouponId"
              >
            </div>
          </div>
          
          <div v-if="availableCoupons.length === 0" class="no-coupons">
            暂无可用优惠券
          </div>
        </div>
        <div class="modal-footer">
          <button 
            class="confirm-btn" 
            @click="confirmCouponSelection"
            :disabled="!selectedCoupon"
          >
            确认使用
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { cartAPI, mycouponsAPI } from '@/http'

const carts = ref([])
const cartNum = ref(0)
const product = ref([])
const coupons = ref([])
const selectedCoupon = ref(null)
const showCouponModal = ref(false)

// 获取购物车数据
const fetchProduct = async () => {
  try {
    const res = await cartAPI.getCartList()
    carts.value = res.data.cartList || []
    cartNum.value = res.data.cartNum || 0
    product.value = res.data.productList || []
    
    // 初始化选中状态
    product.value.forEach(item => {
      item.selected = true
    })

    // 获取优惠券数据
    const couponRes = await mycouponsAPI.getProductList()
    coupons.value = couponRes || []

    console.log('优惠券数据:', coupons.value)
  } catch (error) {
    console.error('获取数据失败:', error)
    product.value = []
    cartNum.value = 0
    coupons.value = []
  }
}

onMounted(() => {
  fetchProduct()
})

// 计算属性
const selectedCount = computed(() => {
  return product.value
    .filter((item, index) => item.selected)
    .reduce((sum, item, index) => sum + (carts.value[index]?.productNum || 0), 0)
})

const totalPrice = computed(() => {
  return product.value
    .filter((item, index) => item.selected)
    .reduce((sum, item, index) => {
      const quantity = carts.value[index]?.productNum || 1
      return sum + (item.productPrice * quantity)
    }, 0)
})

const isAllSelected = computed(() => 
  product.value.length > 0 && product.value.every(item => item.selected)
)

const finalPrice = computed(() => {
  let price = totalPrice.value
  if (selectedCoupon.value) {
    const minCondition = parseMinCondition(selectedCoupon.value.yy)
    if (price >= minCondition) {
      price -= selectedCoupon.value.mycouponPrice
      if (price < 0) price = 0
    } else {
      selectedCoupon.value = null
    }
  }
  return price
})

const availableCoupons = computed(() => {
  return coupons.value.filter(coupon => {
    return coupon.mycouponStatus === 1
  })
})

// 方法
const toggleAllSelection = () => {
  const newState = !isAllSelected.value
  product.value.forEach(item => {
    item.selected = newState
  })
}

const updateSelection = () => {
  // 自动更新全选状态
}

const adjustQuantity = async (productId, delta) => {
  const index = product.value.findIndex(item => item.productId === productId)
  if (index !== -1) {
    const newQty = (carts.value[index].productNum || 1) + delta
    if (newQty > 0) {
      try {
        await cartAPI.updateCartItemQuantity(carts.value[index].cartId, newQty)
        carts.value[index].productNum = newQty
      } catch (error) {
        console.error('更新数量失败:', error)
      }
    }
  }
}

const removeItem = async (productId) => {
  const index = product.value.findIndex(item => item.productId === productId)
  if (index !== -1) {
    try {
      await cartAPI.removeCartItem(carts.value[index].cartId)
      product.value.splice(index, 1)
      carts.value.splice(index, 1)
      cartNum.value -= 1
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }
}

const selectCoupon = (coupon) => {
  selectedCoupon.value = coupon
}

const confirmCouponSelection = () => {
  showCouponModal.value = false
}

const removeCoupon = () => {
  selectedCoupon.value = null
}

const handleCheckout = () => {
  // 结算逻辑
  console.log('结算商品:', product.value.filter(item => item.selected))
  console.log('使用优惠券:', selectedCoupon.value)
  console.log('总金额:', finalPrice.value)
}

const parseCouponName = (coupon) => {
  if (coupon.mycouponPrice >= 5000) {
    return `大额优惠券-减${(coupon.mycouponPrice).toFixed(2)}元`
  }
  return `通用优惠券-减${(coupon.mycouponPrice).toFixed(2)}元`
}

const parseMinCondition = (condition) => {
  if (!condition) return 0
  const match = condition.match(/满(\d+)/)
  return match ? parseInt(match[1]) : 0
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未知日期'
  return dateStr.split('T')[0]
}
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.cart-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.cart-header h2 {
  font-size: 24px;
  margin-right: 15px;
}

.badge {
  background-color: #ff6700;
  color: white;
  padding: 3px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.cart-control {
  padding: 10px;
  background-color: white;
  margin-bottom: 10px;
  border-radius: 4px;
}

.select-all {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.select-all input {
  margin-right: 8px;
}

.items-container {
  background-color: white;
  border-radius: 4px;
  padding: 10px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  position: relative;
}

.item-select {
  margin-right: 15px;
  cursor: pointer;
}

.item-image img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.item-details {
  flex: 1;
  margin-right: 15px;
}

.item-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.item-desc {
  color: #666;
  font-size: 12px;
  margin-bottom: 5px;
}

.item-tags .tag {
  display: inline-block;
  padding: 2px 5px;
  background-color: #f5f5f5;
  color: #ff6700;
  font-size: 12px;
  border-radius: 2px;
}

.item-pricing {
  text-align: right;
  min-width: 150px;
}

.price-row {
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  color: #ff6700;
  font-weight: bold;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-left: 5px;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.qty-btn {
  width: 25px;
  height: 25px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
}

.qty-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.remove-btn {
  position: absolute;
  top: 15px;
  right: 0;
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.remove-btn:hover {
  color: #ff6700;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
}

.empty-cart p {
  margin-bottom: 20px;
  color: #666;
}

.browse-btn {
  padding: 8px 20px;
  background-color: #ff6700;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.coupon-selector {
  margin-top: 15px;
}

.coupon-trigger {
  padding: 8px 15px;
  background-color: white;
  border: 1px solid #ff6700;
  color: #ff6700;
  border-radius: 4px;
  cursor: pointer;
}

.selected-coupon {
  display: inline-flex;
  align-items: center;
}

.remove-coupon {
  margin-left: 5px;
  cursor: pointer;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  transform: translateY(100%);
  transition: transform 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkout-bar.active {
  transform: translateY(0);
}

.price-summary {
  flex: 1;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.summary-row.total {
  font-weight: bold;
  margin-top: 5px;
}

.final-price {
  color: #ff6700;
  font-size: 18px;
}

.discount {
  color: #ff6700;
}

.checkout-btn {
  padding: 12px 30px;
  background-color: #ff6700;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 20px;
}

.checkout-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.coupon-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  width: 90%;
  max-width: 500px;
  border-radius: 8px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 15px;
}

.coupon-card {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 10px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.coupon-card:hover {
  border-color: #ff6700;
}

.coupon-card.selected {
  border: 1px solid #ff6700;
  background-color: #fff8f0;
}

.coupon-value {
  display: flex;
  align-items: center;
  color: #ff6700;
  font-size: 16px;
  margin-right: 15px;
}

.coupon-value .amount {
  font-size: 24px;
  font-weight: bold;
}

.coupon-details {
  flex: 1;
}

.coupon-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.coupon-condition, .coupon-expiry {
  font-size: 12px;
  color: #666;
}

.coupon-selector input[type="radio"] {
  width: 18px;
  height: 18px;
  accent-color: #ff6700;
}

.modal-footer {
  padding: 15px;
  text-align: right;
  border-top: 1px solid #eee;
}

.confirm-btn {
  padding: 8px 20px;
  background-color: #ff6700;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.no-coupons {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>